#include "StdAfx.h"
#include "capture_helper.h"

capture_helper::capture_helper(void)
{
	m_hWnd = NULL;
}

capture_helper::~capture_helper(void)
{
}

bool capture_helper::capture(HWND wnd, CxImage* ptr_img)
{
	m_hWnd = wnd;

	CRect r;
	::GetWindowRect(wnd, &r);

	/// check if the window is out of the screen or maximixed
	int xScreen, yScreen;	
	int xshift = 0; 
	int yshift = 0;

	xScreen = GetSystemMetrics(SM_CXSCREEN);
	yScreen = GetSystemMetrics(SM_CYSCREEN);

	if( r.right > xScreen )
		r.right = xScreen;

	if( r.bottom > yScreen )
		r.bottom = yScreen;

	if( r.left < 0 )
	{
		xshift = -r.left;
		r.left = 0;
	}

	if( r.top < 0 )
	{
		yshift = -r.top;
		r.top = 0;
	}

	CSize sz(r.Width(), r.Height());
	if( sz.cx <= 0 || sz.cy <= 0 ) 
		return false;

	/// bring the window at the top most level
	::SetWindowPos(wnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

	/// prepare the DCs
	HDC dstDC = ::GetDC(NULL);
	HDC srcDC = ::GetWindowDC(wnd); /// full window (::GetDC(hwnd); = clientarea)
	HDC memDC = ::CreateCompatibleDC(dstDC);

	/// copy the screen to the bitmap
	HBITMAP bm =::CreateCompatibleBitmap(dstDC, sz.cx, sz.cy);
	HBITMAP oldbm = (HBITMAP)::SelectObject(memDC, bm);
	::BitBlt(memDC, 0, 0, sz.cx, sz.cy, srcDC, xshift, yshift, SRCCOPY);

	/// restore the position
	::SetWindowPos(wnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);

	ptr_img->CreateFromHBITMAP(bm);

	SelectObject(memDC,oldbm);
	/// free objects
	DeleteObject(bm);
	DeleteObject(memDC);
	DeleteObject(srcDC);
	DeleteObject(dstDC);

	return true;
}